package com.zk.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zk.entity.ResultDto;
import com.zk.entity.User;
import com.zk.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ljw
 * @since 2020-11-29
 */
@RestController
@RequestMapping("/zk/user")
public class UserController {
    @Autowired
    @Qualifier("userServiceImpl")
   private IUserService iUserService;

    /**
     * 添加用户
     */
    @RequestMapping(value = "/",method = RequestMethod.POST)
    public ResultDto<User> insertUser(
            @RequestBody User user
    ) {
        try {
            if(iUserService.save(user)){
                return new ResultDto<>(200, "用户添加成功");
            }else{
                return new ResultDto<>(200, "用户添加失败");
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
            return new ResultDto<>(500, "服务器内部错误");
        }
    }

    /**
     * 删除用户
     */
    @RequestMapping(value = "/",method = RequestMethod.DELETE)
    public ResultDto<User> deleteUser(
            @RequestParam("userId") int userId
    ){
        try{
            if(iUserService.removeById(userId)){
                return new ResultDto<>(200, "用户删除成功");
            }else{
                return new ResultDto<>(200, "用户删除失败");
            }
        }catch (Exception e){
            return new ResultDto<>(500, "服务器内部错误");
        }
    }

    /**
     * 根据userid修改用户
     */
    @RequestMapping(value = "/",method = RequestMethod.PUT)
    public ResultDto<User> update(
            @RequestBody User user
    ){
        try{
            if(iUserService.updateById(user)){
                return new ResultDto<>(200, "用户更新成功");
            }else{
                return new ResultDto<>(200, "用户更新失败");
            }
        }catch (Exception e){
            return new ResultDto<>(500, "服务器内部错误");
        }
    }

    /**
     * 根据ID查询用户
     */
    @RequestMapping(value = "/{userid}",method = RequestMethod.GET)
    public ResultDto<User> queryUserByUserid(
            @PathVariable("userid") int userid
    ){
        try{
            User user = iUserService.getOne(new QueryWrapper<User>().eq("user_id",userid));
            return new ResultDto<>(200, "用户查询成功",user);
        }catch (Exception e){
            System.out.println(e.getMessage());
            return new ResultDto<>(500, "服务器内部错误");
        }

    }

    /**
     * 查询所有用户
     */
    @RequestMapping(value = "/",method = RequestMethod.GET)
    public ResultDto<List<User>> queryAllUser(){
        try{
            List<User> users = iUserService.list();
            return new ResultDto<>(200, "用户查询成功",users);
        }catch (Exception e){

            return new ResultDto<>(500, "服务器内部错误");
        }

    }
}

